<template>
  <el-form class="b-charge-catalog">
    <el-form-item :label="$t('paywall.label.productfamily')">
      <el-select v-model="currentFamily"
                 value-key="otherId"
                 clearable>
        <el-option v-for="item in products"
                   :key="item.otherId"
                   :label="item.name"
                   :value="item">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-table class="b-charge-catalog"
                :header-cell-style="headerCellStyle"
                :show-header="!!chargeCatalogs.length"
                :empty-text="$t('paywall.gsbap')"
                :data="chargeCatalogs">
        <el-table-column prop="items"
                         label="Items">
          <template v-slot:default="{row}">
            <ZTooltip :content="row.name"
                      :line="1">
              <div>{{row.name}}</div>
            </ZTooltip>

            <div>
              <ZIcon icon="us.svg"
                     style="margin-right:8px" />
              <span>{{$t('paywall.usd')}}</span>,
              <span>{{row.type}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="amount"
                         label="Amount"
                         align="right">
          <template v-slot:default="{row}">
            <div v-for="item in row.chargebeeItemPricesList"
                 :key="item.otherId">
              <span v-if="item.price">{{item.price / 100}}</span>
              <span v-if="item.periodUnit && item.price">/</span>
              <span v-if="item.periodUnit">{{item.periodUnit}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="action"
                         label="Action"
                         width="130">
          <template v-slot:default="{row,$index}">
            <el-button type="text"
                       @click="open(row.type,'edit',row)">{{$t('paywall.edit')}}</el-button>
            <el-button type="text"
                       @click="remove($index)">{{$t('paywall.remove')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div :class="['b-charge-catalog-rack flex items-center',{
            'b-charge-catalog-rack--disabled':!currentFamily
      }]">

        <el-button icon="el-icon-circle-plus-outline"
                   type="text"
                   v-if="!hasPlan"
                   @click="open('plan','add')">{{$t('paywall.addPlan')}}</el-button>
        <template v-else>
          <el-button type="text"
                     @click="open('addon','add')"
                     icon="el-icon-circle-plus-outline">{{$t('paywall.addRecurringAddon')}}</el-button>
          <el-divider direction="vertical"
                      style="margin:0 10px"></el-divider>
          <el-button type="text"
                     @click="open('charge','add')"
                     icon="el-icon-circle-plus-outline">Add Charge</el-button>
        </template>

      </div>
    </el-form-item>

    <el-dialog :visible.sync="visible"
               destroy-on-close
               width="560px"
               custom-class="b-charge-catalog-dialog"
               append-to-body
               @closed="closed">
      <template v-slot:title>
        <div class="b-charge-catalog-dialog--title">
          <ZIcon icon="el-icon-arrow-left"
                 class="cursor-pointer"
                 @click.native="back"
                 v-if="product&&product.type!=='charge'" />
          {{dialogTitle}}
        </div>
        <el-input placeholder="Search"
                  prefix-icon="el-icon-search"
                  class="b-charge-catalog-dialog--search"
                  v-model="searchKey"
                  v-if="!product"></el-input>
      </template>
      <div class="b-charge-catalog-list flex flex-col">
        <el-table :show-header="false"
                  v-if="!product"
                  class="b-charge-catalog-table"
                  :cell-style="cellStyle"
                  @row-click="rowClick"
                  :data="list">
          <el-table-column prop="name"></el-table-column>
        </el-table>

        <el-form v-else
                 label-position="top"
                 class="b-charge-catalog-form flex-1">
          <el-form-item :label="$t('paywall.label.cacft')">
            <el-select v-model="charge"
                       clearable
                       value-key="otherId"
                       multiple
                       collapse-tags>
              <el-option :value="item"
                         :label="item.name"
                         class="flex items-center"
                         v-for="item in product.chargebeeItemPricesList"
                         :key="item.otherId">
                <ZIcon icon="us.svg"
                       style="margin-right:8px" />
                <span>{{item.currencyCode}}</span>

                <span class="flex-1 text-right">
                  <span v-if="item.price">{{item.price / 100}}</span>
                  <span v-if="item.periodUnit && item.price">/</span>
                  <span v-if="item.periodUnit">{{item.periodUnit}}</span>
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer"
              class="dialog-footer"
              v-if="product">
          <el-button size="small"
                     @click="close">{{$t('paywall.cancel')}}</el-button>
          <el-button type="primary"
                     size="small"
                     @click="save"
                     :disabled="!charge.length">{{$t('paywall.add')}}</el-button>
        </span>
      </div>
    </el-dialog>

  </el-form>
</template>

<script>
import ZIcon from '@/components/storybook/z-icon'
import ZTooltip from '@/components/storybook/z-tooltip'
import { productCatalog } from './index.schema'
import { get, toLower, omit, cloneDeep } from 'lodash'

export default {
  name: 'BChargeCatalog',
  components: {
    ZIcon,
    ZTooltip
  },
  props: {
    chargeCatalogs: {
      type: Array,
      default: () => ([])
    },
    products: {
      type: Array,
      default: () => ([])
    },
    family: {
      type: Object
    }

  },
  data () {
    return {

      // charge type
      mode: undefined,

      // add or update
      type: undefined,

      product: undefined,

      charge: [],

      searchKey: undefined

    }
  },

  computed: {
    visible: {
      get () {
        return !!this.type
      },
      set (val) {
        const value = val || undefined
        this.type = value
      }
    },
    currentFamily: {
      get () {
        return this.family
      },
      set (val) {
        this.$emit('update:family', val)
      }
    },
    dialogTitle () {
      if (this.product && this.product.type !== 'charge') {
        return `Config ${this.product.name}`
      }
      return `Add ${productCatalog[this.mode]}`
    },

    hasPlan () {
      return this.chargeCatalogs.some(i => i.type === 'plan')
    },
    list () {
      const items = get(this.currentFamily, 'chargebeeItems') || []
      const selected = (item) => this.chargeCatalogs.some(i => i.otherId === item.otherId)
      return items.filter(i => (
        i.type === this.mode &&
        i.status === 'active' &&
        i.chargebeeItemPricesList &&
        i.chargebeeItemPricesList.length &&
        toLower(i.name).indexOf(toLower(this.searchKey)) !== -1 &&
        !selected(i)
      ))
    }

  },

  methods: {
    headerCellStyle () {
      return {
        padding: '0',
        fontSize: '12px',
        fontWeight: '400',
        color: '#64648c',
        whiteSpace: 'nowrap'
      }
    },
    cellStyle () {
      return {
        padding: '12px 16px',
        cursor: 'pointer'

      }
    },

    open (mode, type, row) {
      if (row) {
        if (mode !== 'plan') {
          const items = get(this.currentFamily, 'chargebeeItems') || []
          const cloneRow = items.find(i => i.otherId === row.otherId)
          this.product = cloneDeep(cloneRow)
        }
        this.charge = row.chargebeeItemPricesList
      }
      this.mode = mode
      this.type = type
    },
    close () {
      this.type = undefined
    },
    closed () {
      this.product = undefined
      this.mode = undefined
      this.charge = []
    },
    remove (index) {
      this.chargeCatalogs.splice(index, 1)
    },
    back () {
      this.product = undefined
      this.searchKey = undefined
      this.charge = []
    },
    rowClick (row) {
      this.product = row
      this.searchKey = undefined
    },
    save () {
      const item = omit(this.product, 'chargebeeItemPricesList')
      item.chargebeeItemPricesList = this.charge

      if (this.type === 'edit') {
        const index = this.chargeCatalogs.findIndex(i => i.otherId === item.otherId)
        this.chargeCatalogs.splice(index, 1, item)
      } else {
        this.chargeCatalogs.push(item)
      }

      this.close()
    }

  }
}
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.b-charge-catalog {
  &-table {
    overflow: initial;
  }
  &-rack {
    height: 47px;
    border: 1px solid #dbe6ff;
    background: #f4f7fc;
    border-radius: 4px;
    padding: 0 20px;
    &--disabled {
      pointer-events: none;
      box-shadow: none !important;
      filter: grayscale(100%) !important;
    }
  }
  &-dialog--title {
    font-weight: 500;
    font-size: 20px;
  }
  &-dialog--search {
    margin-top: 16px;

    ::v-deep .el-input__inner {
      height: 38px;
      line-height: 38px;
    }
  }
  &-list {
    padding-bottom: 8px;
    border-top: 1px solid #d4d4e8;
    max-height: 553px;
    min-height: 448px;
    overflow-y: auto;
  }
  &-form {
    padding: 36px 20px 0;
  }
}
</style>
<style lang="scss">
.b-charge-catalog-dialog {
  .el-dialog__body {
    padding: 10px 0 0;
  }
}
</style>
